-- stuff we use
local _assert, tonumber, tostring, type, ipairs, string, pairs, unpack = _assert, tonumber, tostring, type, ipairs, string, pairs, unpack

local oo = require("loop.base")

local Popup                  = require("jive.ui.Popup")
local Label                  = require("jive.ui.Label")
local Window                 = require("jive.ui.Window")

local debug = require("jive.utils.debug")
local log = require("jive.utils.log").logger("jrmc")

-- our class
module(..., oo.class)



-- init
-- creates an empty database object
function __init(self, theApplet)
	tostring("test")
	log:error("SqueezeOutputHandler:__init()")
	self.applet = theApplet;
	return oo.rawnew(self, {})
end



function play(self, menuItem)
	if (menuItem.isFolder) then
		self.applet:getAllTracks(menuItem.location, playMultiple)
	else
		--just one track to do
		self:jsonRequest({ "playlist", "play", "file:///" .. self:getFilePath(menuItem.file)})
	end
	return true		
end

function playMultiple(self, jrmcItems)
	self:jsonRequest({ "playlist", "playtracks", "listref", self:getPaths(jrmcItems)})	   
end

function addEnd(self, menuItem)
	if (menuItem.isFolder) then
		self.applet:getAllTracks(menuItem.location, addEndMultiple)
	else
		self:jsonRequest({ "playlist", "add", "file:///" .. self:getFilePath(menuItem.file)})
	end
	
	return true		
end


function addEndMultiple(self, jrmcItems)
	self:jsonRequest({ "playlist", "addtracks", "listref", self:getPaths(jrmcItems)})	   
end

function pause(self)
	return false
end

function stop(self)
	return false
end

function next(self)
	return false
end

function previous(self)
	return false
end

function volumeUp(self)
	return false
end

function volumeDown(self)
	return false
end

function handleHomeKey(self)
	return false
end



function __tostring(self)
	return "SqueezeOutputHandler"
end


function getPaths(self, urlItems)
	local paths = {}
	for i,urlItem in ipairs(urlItems) do
		local path = "file:///" .. self:getFilePath(urlItem.file)
		if not containsProblemChar(path) then
			paths[i] = path
		else
			log:error("Problem char found, skipping this file:" , path)		
		end	
	end
	
	return paths
end

function getFilePath(self, file)
--	querystring = string.gsub(url, "play%?", "")
	file = unescape(file)
	file = string.gsub(file, "\\", "/")
	return string.gsub(file, " ", "%%20")
end

function jsonRequest(self, request)
	
	--debug.dump(request)
	local filepath = request[3]
	if (filepath and containsProblemChar(filepath)) then

		log:error("Problem char found, skipping this file:" , filepath)
		return
	end
	
	self.applet.server:request( function(chunk, err)
									if err then
										log:error("error sending JSON")
									end
									if chunk then
										log:debug("JSON response received for ", request[1], request[2], request[3])
									end
								end
								, self.applet.player:getId(), request)

end

function containsProblemChar(urlDecodedString)
	for i = 1,string.len(urlDecodedString) do
		if (string.byte(urlDecodedString, i) > 127) then 
			return true
		end
	end
	
	return false
end

function unescape (s)
  s = string.gsub(s, "+", " ")
  s = string.gsub(s, "%%(%x%x)", function (h)
        return string.char(tonumber(h, 16))
      end)
  return s
end
